<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <todo-header @insertTodo="insertTodo"></todo-header>
      <todo-list :todos="todos"></todo-list>
      <todo-footer :todos="todos"
                   @selectAll="selectAll"
                   @deleteChecked="deleteChecked">
      </todo-footer>
    </div>
  </div>
</template>

<script>
  import header from './components/header'
  import list from './components/list'
  import footer from './components/footer'
  import PubSub from 'pubsub-js'
  import Util from './utils'
  export default {
    name: "App",
    data(){
      return {
        todos:[
          {id:1,text:"Eating",completed:false},
          {id:2,text:"Swimming",completed:false},
          {id:3,text:"Computer",completed:false},
          {id:4,text:"Sleeping",completed:false},
          {id:5,text:"Shopping",completed:false}
        ]
      }
    },
    methods:{
      insertTodo(todoMsg){
        this.todos.unshift(todoMsg)
      },
      deleteChecked(){
        this.todos = this.todos.filter((todo)=>{
          return !todo.completed
        })
      },
      selectAll(val){
        this.todos.forEach((item)=>{
          item.completed = val
        })
      }
    },
    mounted() {
      PubSub.subscribe("delete",(msg,id)=>{
        this.todos = this.todos.filter((item)=>{
          return item.id !== id
        })
      })
      PubSub.subscribe("todoCompleted",(msg,obj)=>{
        this.todos.forEach((item)=>{
          if(item.id === obj.id){
            item.completed = obj.val
          }
        })
      })
  
      this.todos = Util.getTodos();
    },
    components:{
      "todo-header": header,
      "todo-list": list,
      "todo-footer": footer
    },
    watch:{
      todos:{
        deep:true,
        handler(newVal){
          ///往localStorage中设置数据
          Util.setTodos(newVal)
        }
      }
    }
  }
</script>

<style scoped>
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>
